import 'dart:io';
import 'package:azring/gen/assets.gen.dart';
import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:smooth_page_indicator/smooth_page_indicator.dart';
import 'InsightsLogic.dart';
import 'chat_message.dart';

/// 洞察页面
class InsightsView extends GetView<InsightsLogic> {
  const InsightsView({super.key});

  Widget _buildView() {
    return Container(
      color: Colors.black,
      child: SingleChildScrollView(
        child: Column(
          children: [
            Container(
              width: double.infinity,
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/insight/insight_bcg.png'),
                  fit: BoxFit.cover,
                ),
              ),
              child: SafeArea(
                child: Padding(
                  padding: EdgeInsets.all(16.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      _buildHeader(),
                      SizedBox(height: 20.h),
                      _buildTitle(),
                      SizedBox(height: 30.h),
                      _buildReportButtons(),
                      SizedBox(height: 20.h),
                      _buildBannerCarousel(),
                    ],
                  ),
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 0.h),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildNoticeButton(),
                  SizedBox(height: 35.h),
                  _buildAIAssistant(),
                  SizedBox(height: 17.h),
                  _buildAIChatCard(),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          '洞察',
          style: TextStyle(
            fontSize: 26.sp,
            fontWeight: FontWeight.w500,
            color: Colors.white,
          ),
        ),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          decoration: BoxDecoration(
            border: Border.all(color: Colors.white.withOpacity(0.5)),
            borderRadius: BorderRadius.circular(20.r),
          ),
          child: Row(
            children: [
              Icon(
                Icons.wb_sunny_outlined,
                color: Colors.white,
                size: 20.sp,
              ),
              SizedBox(width: 6.w),
              Text(
                '环境',
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Color(0xffDEDEDE),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildTitle() {
    return Center(
      child: Text(
        '身体趋势报告',
        style: TextStyle(
          fontSize: 26.sp,
          fontWeight: FontWeight.w500,
          color: Colors.white,
        ),
      ),
    );
  }

  Widget _buildReportButtons() {
    return Row(
      children: [
        Expanded(
          child: _buildReportButton('周报'),
        ),
        SizedBox(width: 20.w),
        Expanded(
          child: _buildReportButton('月报'),
        ),
      ],
    );
  }

  Widget _buildReportButton(String title) {
    return Container(
      width: 167.w,
      height: 39.h,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(100.r),
        border: Border.all(
          color: Colors.white,
          width: 1,
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 9,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            title,
            style: TextStyle(
              fontSize: 16.sp,
              color: Colors.white,
              fontWeight: FontWeight.w500,
            ),
          ),
          SizedBox(width: 8.w),
          Icon(
            Icons.keyboard_arrow_down,
            color: Colors.white,
            size: 20.sp,
          ),
        ],
      ),
    );
  }

  Widget _buildBannerCarousel() {
    final banners = [
      Assets.insight.banner1,
      Assets.insight.banner2,
      Assets.insight.banner3,
      Assets.insight.banner4,
      Assets.insight.banner5,
      Assets.insight.banner6,
    ];

    return SizedBox(
      width: 353.w,
      height: 419.h,
      child: Column(
        children: [
          Expanded(
            child: PageView.builder(
              controller: controller.pageController,
              itemCount: banners.length,
              itemBuilder: (context, index) {
                return Padding(
                  padding: EdgeInsets.symmetric(horizontal: 8.w),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(12.r),
                    child: banners[index].image(
                      fit: BoxFit.cover,
                      width: double.infinity,
                    ),
                  ),
                );
              },
            ),
          ),
          SizedBox(height: 12.h),
          SmoothPageIndicator(
            controller: controller.pageController,
            count: banners.length,
            effect: ExpandingDotsEffect(
              dotHeight: 6.h,
              dotWidth: 6.w,
              activeDotColor: Colors.white,
              dotColor: Colors.white.withOpacity(0.3),
              expansionFactor: 3,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildNoticeButton() {
    return Container(
      width: double.infinity,
      height: 50.h,
      decoration: BoxDecoration(
        color: const Color(0xFFFF6B35),
        borderRadius: BorderRadius.circular(25.r),
      ),
      child: Center(
        child: Text(
          '报告功能暂未上线，敬请期待',
          style: TextStyle(
            fontSize: 16.sp,
            color: Colors.white,
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
    );
  }

  Widget _buildAIAssistant() {
    return GestureDetector(
      onTap: () => controller.toggleAIFullScreen(),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            '小A管家',
            style: TextStyle(
              fontSize: 22.sp,
              color: const Color(0xffDEDEDE),
              fontWeight: FontWeight.w500,
            ),
          ),
          Assets.insight.expandText.image(width: 24.w, height: 24.h)
        ],
      ),
    );
  }

  Widget _buildAIChatCard() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(8.w),
      decoration: BoxDecoration(
        color: const Color(0xFF282528),
        borderRadius: BorderRadius.circular(16.r),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 如果有消息，显示消息列表；否则显示欢迎界面
          Obx(() {
            if (controller.state.messages.isEmpty) {
              return Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Assets.insight.smileA.image(width: 83.w, height: 70.h),
                  SizedBox(height: 20.h),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        'Hi',
                        style: TextStyle(
                          fontSize: 18.sp,
                          color: Colors.grey[400],
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                      SizedBox(width: 6.w),
                      Text(
                        '👋',
                        style: TextStyle(fontSize: 18.sp),
                      ),
                    ],
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    '遇到困扰了么？',
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: Colors.grey[400],
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    '不确定的事情可以问我哦~',
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: Colors.grey[400],
                      fontWeight: FontWeight.w400,
                    ),
                  ),
                  SizedBox(height: 40.h),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      _buildQuickButton('月报告'),
                      SizedBox(width: 18.w),
                      _buildQuickButton('中医体质检测'),
                      SizedBox(width: 18.w),
                      _buildQuickButton('健康问答'),
                    ],
                  ),
                ],
              );
            } else {
              // 显示消息列表（最多显示最近3条）
              final recentMessages = controller.state.messages.length > 3
                  ? controller.state.messages
                      .sublist(controller.state.messages.length - 3)
                  : controller.state.messages;

              return Container(
                constraints: BoxConstraints(maxHeight: 200.h),
                child: ListView.builder(
                  shrinkWrap: true,
                  itemCount: recentMessages.length,
                  itemBuilder: (context, index) {
                    return _buildMessageBubble(recentMessages[index]);
                  },
                ),
              );
            }
          }),
          SizedBox(height: 12.h),
          // Chat input - 使用共用的输入栏组件
          _buildChatInputBar(),
        ],
      ),
    );
  }

  Widget _buildQuickButton(String text) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
      decoration: BoxDecoration(
        border: Border.all(color: Colors.grey[700]!),
        borderRadius: BorderRadius.circular(7.r),
      ),
      child: Text(
        text,
        style: TextStyle(
          fontSize: 12.sp,
          color: Colors.grey[500],
        ),
      ),
    );
  }

  /// 构建附件选项
  Widget _buildAttachmentOption({
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            width: 60.w,
            height: 60.w,
            decoration: BoxDecoration(
              color: const Color(0xFF2A2A2A),
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: Icon(
              icon,
              color: Colors.white,
              size: 28.sp,
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            label,
            style: TextStyle(
              fontSize: 12.sp,
              color: Colors.grey[400],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建消息气泡
  Widget _buildMessageBubble(ChatMessage message) {
    final isUser = message.sender == MessageSender.user;

    return Padding(
      padding: EdgeInsets.only(bottom: 16.h),
      child: Row(
        mainAxisAlignment:
            isUser ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            constraints: BoxConstraints(maxWidth: 280.w),
            padding: EdgeInsets.all(16.w),
            decoration: BoxDecoration(
              color: isUser ? const Color(0xFF4A90E2) : const Color(0xFF2B2826),
              borderRadius: BorderRadius.circular(16.r),
              border: Border.all(width:1,color: isUser ? Colors.transparent : const Color(0xff554133))
            ),
            child: message.isThinking
                ? Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      SizedBox(
                        width: 16.w,
                        height: 16.w,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(
                            Colors.grey[400]!,
                          ),
                        ),
                      ),
                      SizedBox(width: 8.w),
                      Text(
                        message.content,
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: Colors.grey[400],
                        ),
                      ),
                    ],
                  )
                : message.type == MessageType.voice
                    ? _buildVoiceMessage(message)
                    : message.type == MessageType.image
                        ? _buildImageMessage(message)
                        : message.type == MessageType.file
                            ? _buildFileMessage(message)
                            : Text(
                                message.content,
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: Colors.white,
                                ),
                              ),
          ),
        ],
      ),
    );
  }

  /// 构建语音消息
  Widget _buildVoiceMessage(ChatMessage message) {
    return Obx(() {
      final isPlaying = controller.state.playingVoiceId.value == message.id;

      return GestureDetector(
        onTap: () {
          if (message.fileUrl != null) {
            controller.playVoice(message.id, message.fileUrl!);
          }
        },
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              isPlaying ? Icons.pause_circle : Icons.play_circle,
              color: Colors.white,
              size: 32.sp,
            ),
            SizedBox(width: 8.w),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  width: 100.w,
                  height: 20.h,
                  decoration: BoxDecoration(
                    color: Colors.white.withValues(alpha: 0.3),
                    borderRadius: BorderRadius.circular(10.r),
                  ),
                  child: isPlaying
                      ? LinearProgressIndicator(
                          backgroundColor: Colors.transparent,
                          valueColor: AlwaysStoppedAnimation<Color>(
                            Colors.white.withValues(alpha: 0.6),
                          ),
                        )
                      : null,
                ),
                SizedBox(height: 4.h),
                Text(
                  message.content,
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.white.withValues(alpha: 0.8),
                  ),
                ),
              ],
            ),
          ],
        ),
      );
    });
  }

  /// 构建图片消息
  Widget _buildImageMessage(ChatMessage message) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ClipRRect(
          borderRadius: BorderRadius.circular(8.r),
          child: Image.file(
            File(message.imageUrl ?? ''),
            width: 200.w,
            fit: BoxFit.cover,
            errorBuilder: (context, error, stackTrace) {
              return Container(
                width: 200.w,
                height: 150.h,
                color: Colors.grey[800],
                child: Icon(
                  Icons.broken_image,
                  color: Colors.grey[600],
                  size: 48.sp,
                ),
              );
            },
          ),
        ),
        if (message.content.isNotEmpty) ...[
          SizedBox(height: 8.h),
          Text(
            message.content,
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.white,
            ),
          ),
        ],
      ],
    );
  }

  /// 构建文件消息
  Widget _buildFileMessage(ChatMessage message) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.insert_drive_file,
              color: Colors.white,
              size: 32.sp,
            ),
            SizedBox(width: 8.w),
            Flexible(
              child: Text(
                message.fileName ?? message.fileUrl?.split('/').last ?? '文件',
                style: TextStyle(
                  fontSize: 14.sp,
                  color: Colors.white,
                ),
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
        if (message.content.isNotEmpty) ...[
          SizedBox(height: 8.h),
          Text(
            message.content,
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.white,
            ),
          ),
        ],
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Obx(() {
        if (controller.state.isAIFullScreen.value) {
          return _buildFullScreenAIChat();
        }
        return _buildView();
      }),
    );
  }

  /// 构建全屏小A管家聊天界面
  Widget _buildFullScreenAIChat() {
    return Container(
      decoration: const BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/insight/conversation_bg.png'),
          fit: BoxFit.cover,
        ),
      ),
      child: SafeArea(
        child: Column(
          children: [
            // 顶部标题栏
            Container(
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '小A管家',
                    style: TextStyle(
                      fontSize: 20.sp,
                      color: Colors.white,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  GestureDetector(
                      onTap: () => controller.toggleAIFullScreen(),
                      child: Assets.insight.collapseTextInput
                          .image(width: 24.w, height: 24.h)),
                ],
              ),
            ),
            Divider(
              color: Colors.grey[800],
              height: 1,
            ),
            // 聊天内容区域
            Expanded(
              child: Obx(() => ListView.builder(
                    padding: EdgeInsets.all(16.w),
                    itemCount: controller.state.messages.length,
                    itemBuilder: (context, index) {
                      final message = controller.state.messages[index];
                      return _buildMessageBubble(message);
                    },
                  )),
            ),
            // 底部输入栏
            _buildChatInputBar(),
          ],
        ),
      ),
    );
  }

  /// 构建聊天输入栏（全屏和半屏共用）
  Widget _buildChatInputBar() {
    return Obx(() => Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 输入栏
            Container(
              padding: EdgeInsets.all(10.w),
              decoration: const BoxDecoration(
                  color: Color(0xFF1A1A1A),
                  borderRadius: BorderRadius.all(Radius.circular(12))),
              child: Row(
                children: [
                  // 左侧按钮：语音/键盘切换
                  GestureDetector(
                    onTap: controller.toggleInputMode,
                    child: Center(
                      child: controller.state.isVoiceMode.value
                          ? Icon(
                              Icons.keyboard,
                              color: Colors.white,
                              size: 20.sp,
                            )
                          : Assets.insight.speak.image(
                              width: 20.w,
                              height: 20.h,
                            ),
                    ),
                  ),
                  SizedBox(width: 12.w),
                  // 中间输入区域
                  Expanded(
                    child: controller.state.isVoiceMode.value
                        ? GestureDetector(
                            onLongPressStart: (_) =>
                                controller.startRecording(),
                            onLongPressEnd: (_) => controller.stopRecording(),
                            child: Container(
                              padding: EdgeInsets.symmetric(
                                horizontal: 16.w,
                                vertical: 12.h,
                              ),
                              decoration: BoxDecoration(
                                color: controller.state.isRecording.value
                                    ? const Color(0xFF4A90E2)
                                    : const Color(0xFF2A2A2A),
                                borderRadius: BorderRadius.circular(20.r),
                              ),
                              child: Center(
                                child: Obx(() => Text(
                                      controller.state.isRecording.value
                                          ? '松开结束 ${controller.state.recordDuration.value}s'
                                          : '按住说话',
                                      style: TextStyle(
                                        fontSize: 14.sp,
                                        color: Colors.white,
                                      ),
                                    )),
                              ),
                            ),
                          )
                        : Container(
                            padding: EdgeInsets.symmetric(
                              horizontal: 16.w,
                              vertical: 10.h,
                            ),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(20.r),
                            ),
                            child: TextField(
                              controller: controller.textController,
                              style: TextStyle(
                                fontSize: 14.sp,
                                color: Colors.white,
                              ),
                              decoration: InputDecoration(
                                hintText: '发消息...',
                                hintStyle: TextStyle(
                                  fontSize: 14.sp,
                                  color: Colors.grey[600],
                                ),
                                border: InputBorder.none,
                                contentPadding: EdgeInsets.zero,
                                isDense: true,
                              ),
                              onChanged: (text) {
                                controller.state.hasText.value =
                                    text.trim().isNotEmpty;
                              },
                              onSubmitted: (_) => controller.sendTextMessage(),
                            ),
                          ),
                  ),
                  SizedBox(width: 12.w),
                  // 右侧按钮：附件/发送
                  Obx(() => GestureDetector(
                        onTap: () {
                          // 如果有文本内容，发送消息；否则切换附件菜单
                          if (controller.state.hasText.value) {
                            controller.sendTextMessage();
                          } else {
                            controller.toggleAttachmentMenu();
                          }
                        },
                        
                          child: Center(
                            child: controller.state.isSending.value
                                ? SizedBox(
                                    width: 20.w,
                                    height: 20.w,
                                    child: const CircularProgressIndicator(
                                      strokeWidth: 2,
                                      valueColor: AlwaysStoppedAnimation<Color>(
                                        Colors.white,
                                      ),
                                    ),
                                  )
                                : Icon(
                                    controller.state.hasText.value
                                        ? Icons.send
                                        : (controller
                                                .state.showAttachmentMenu.value
                                            ? Icons.close
                                            : Icons.add),
                                    color: Colors.white,
                                    size: 24.sp,
                                  ),
                          ),
                        
                      )),
                ],
              ),
            ),
            // 附件菜单（在输入框下方）
            if (controller.state.showAttachmentMenu.value)
              Container(
                padding: EdgeInsets.all(12.w),
                decoration: BoxDecoration(
                  color: const Color(0xFF1A1A1A),
                  border: Border(
                    bottom: BorderSide(
                      color: Colors.grey[800]!,
                      width: 1,
                    ),
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    _buildAttachmentOption(
                      icon: Icons.camera_alt,
                      label: '拍照',
                      onTap: controller.selectCamera,
                    ),
                    _buildAttachmentOption(
                      icon: Icons.photo_library,
                      label: '上传照片',
                      onTap: controller.selectPhoto,
                    ),
                    _buildAttachmentOption(
                      icon: Icons.insert_drive_file,
                      label: '上传文件',
                      onTap: controller.selectFile,
                    ),
                  ],
                ),
              ),
          ],
        ));
  }
}
